package web.suzy.oj.manager.oj;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import web.suzy.oj.common.exception.StatusFailException;
import web.suzy.oj.dao.problem.ProblemEntityService;
import web.suzy.oj.pojo.entity.problem.Problem;
import web.suzy.oj.pojo.vo.ProblemVO;
import web.suzy.oj.pojo.vo.RandomProblemVO;

import java.util.List;
import java.util.Random;

/**
 * YangSuzy 软件工作室
 * 类名: ProblemManager
 * 描述: ---- 待定 -----
 * 功能: ---- 待定 -----
 * ===========未完成=============
 *
 * @author YangSuzy
 * Date: 2022/11/22 21:47
 */
@Component
public class ProblemManager {
    @Autowired
    private ProblemEntityService problemEntityService;

    /**
     * 方法名: getProblemList
     * 描述: 获取题目列表
     *
     * @param limit       每页显示数目
     * @param currentPage 当前页
     * @param keyword     关键字
     * @param tagId       标签ID
     * @param difficulty  难度
     * @return com.baomidou.mybatisplus.extension.plugins.pagination.Page<web.suzy.oj.pojo.vo.ProblemVO>
     * @date 2022/11/22 21:49
     * @auther YangSuzy
     **/
    public Page<ProblemVO> getProblemList(Integer limit, Integer currentPage,
                                          String keyword, List<Long> tagId, Integer difficulty) {
        //设置默认页码和每页默认显示数目
        if (currentPage == null || currentPage < 1) {
            currentPage = 1;
        }
        if (limit == null || limit < 1) {
            limit = 10;
        }
        //筛选关键字
        if (!StringUtils.isEmpty(keyword)) {
            keyword = keyword.trim();
        }
        return problemEntityService.getProblemList(
                limit, currentPage, null, keyword, difficulty, tagId);
    }

    /**
     * 方法名: getRandomProblem
     * 描述: 随机获取一道题目
     *
     * @return web.suzy.oj.pojo.vo.RandomProblemVO
     * @date 2022/11/22 22:54
     * @auther YangSuzy
     **/
    public RandomProblemVO getRandomProblem() throws StatusFailException {
        //查询所有公开题目
        QueryWrapper<Problem> queryWrapper = new QueryWrapper<>();
        queryWrapper.select("problem_id").eq("auth", 1);
        List<Problem> list = problemEntityService.list(queryWrapper);
        if (list.size() == 0) {
            throw new StatusFailException("获取随机题目失败，题库暂无公开题目！");
        }
        //随机在公开题目列表中取得下标
        Random random = new Random();
        int index = random.nextInt(list.size());
        RandomProblemVO randomProblemVo = new RandomProblemVO();
        randomProblemVo.setProblemId(list.get(index).getProblemId());
        return randomProblemVo;
    }
}
